#include <stdio.h>
#include <memory.h>
#include "FramePool.hxx"

FramePool::FramePool()
{
    _pageCount = 50;
    _pageSize = 0;
    _pool = 0;
}

FramePool::~FramePool()
{
	if( _pool ) 
		free( _pool );
	_pool = 0;
}

void FramePool::clear()
{
	std::queue<int> fempty;
	std::queue<int> pempty;
	
	std::swap(_freeKeys, fempty);
	std::swap(_poolKeys, pempty);

	for( int i = 0; i < _pageCount; i ++ )
    {
        _freeKeys.push( i );
    }
}

void FramePool::initialize()
{
	_freeKeys.empty();
	_poolKeys.empty();

	if( _pool ) free( _pool );
	_pool = (char*)malloc( _pageCount * _pageSize );

	for (int i = 0; i < _pageCount; i++)
	{
		_freeKeys.push(i);
	}
}

bool FramePool::pushFrame(const char *buf)
{
    if( _freeKeys.size() > 0 )
    {
        _keyMutex.lock();
        
		int key = _freeKeys.front();
        _freeKeys.pop();
        _poolKeys.push( key );
		memcpy( _pool + _pageSize * key, buf, _pageSize );
        
		_keyMutex.unlock();
        
        return true;
    }
    else
    {
		printf("Lost a frame...\n");
        return false;
    }
}

bool FramePool::popFrame(char *buf)
{
	int sz = _poolKeys.size();
    if( sz > 0 )
    {
        _keyMutex.lock();

        int key = _poolKeys.front();
        _poolKeys.pop();
        _freeKeys.push( key );
        

        memcpy( buf, _pool + _pageSize * key, _pageSize );

        _keyMutex.unlock();
        return true;
    }
    else
    {
		//printf("Pool is empty!!!\n");
        return false;
    }
}

bool FramePool::isFull()
{
	return _freeKeys.size() <= 0;
}
